package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.User;
import com.itheima.service.UserControlService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/usercontrol")
public class UserControlController {
    @Reference
    private UserControlService userControlService;

    //新增用户
    @RequestMapping("/add")
    public Result add(@RequestBody User user){

        try{
            userControlService.add(user);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, "新增用户失败");
        }
        return new Result(true,"新增用户成功");

    }

    //分页查询
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) throws Exception {

        PageResult pageResult=userControlService.pageQuery(queryPageBean.getCurrentPage(),queryPageBean.getPageSize(),queryPageBean.getQueryString());

        return pageResult;

    }

    //删除操作
    @RequestMapping("/delete")
    @PreAuthorize("hasAuthority('USER_DELETE')")
    public Result delete(Integer id){

        try{
            userControlService.delete(id);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, "删除用户失败");
        }
        return new Result(true,"删除用户成功");

    }


    //根据id查询数据.完成回显
    @RequestMapping("/findById")
    public Result findById(Integer id){
        try{
            User user=userControlService.findById(id);
            return new Result(true,"查询用户成功",user);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, "查询用户失败");
        }

    }

    //修改用户信息
    @RequestMapping("/edit")
    public Result edit(@RequestBody User user){
        System.out.println(user);
        try{
            userControlService.edit(user);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, "修改用户信息失败");
        }
        return new Result(true,"修改用户信息成功");


    }

    //查询所有数据
    @RequestMapping("/findAll")
    public Result findAll(){
        try{
            List<User> user=userControlService.findAll();
            return new Result(true,"查询用户成功",user);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, "查询用户失败");
        }

    }
}
